#!/bin/sh
# shellcheck shell=dash disable=SC2169,SC3010 source=/dev/null
#
# Starts rfd.
#

LOGLEVEL_RFD=5
CFG_TEMPLATE_DIR=/etc/config_templates
PIDFILE=/var/run/rfd.pid

[[ -r /var/hm_mode ]] && . /var/hm_mode

# skip this startup if not in normal mode
[[ "${HM_MODE}" != "NORMAL" ]] && exit 0

init() {

  if [[ ! -d /etc/config/rfd ]]; then
    mkdir -p /etc/config/rfd
  fi

  # Migration for existing rfd.conf in user space
  if [[ ! -e /etc/config/rfd.conf ]]; then
    cp -a ${CFG_TEMPLATE_DIR}/rfd.conf /etc/config/rfd.conf
  fi

  # Bug fixing user spoiled config file
  if grep -q "/etc/config/rfd/keys" /etc/config/rfd.conf; then
    cp -a ${CFG_TEMPLATE_DIR}/rfd.conf /etc/config/rfd.conf
  fi

  # Cleanup rfd.conf (e.g. remove duplicate newlines)
  sed -i '/^$/N;/^\n$/D' /etc/config/rfd.conf

  # only modify if real rf module found
  if [[ "${HM_HMRF_DEV}" == "HM-MOD-RPI-PCB" ]] ||
     [[ "${HM_HMRF_DEV}" == "RPI-RF-MOD" ]] ||
     [[ "${HM_HMRF_DEV}" == "HMIP-RFUSB" ]]; then

    # check if /dev/mmd_bidcos is there
    if [[ -c /dev/mmd_bidcos ]]; then
      # check if commented out "#[Interface 0]" exists now and if not add it
      if grep -q -e "^#\[Interface 0\]" /etc/config/rfd.conf; then
        # commented "#[Interface 0]" section found, uncomment
        sed -i -e '/^#\[Interface 0\]/,/^#\s*$/ s/^#//' /etc/config/rfd.conf
      elif ! grep -q -e "^\[Interface 0\]" /etc/config/rfd.conf; then
        # no uncommented "[Interface 0]" found, add fresh section from config_templates
        sed -n '/^\[Interface 0\]/,/^\s*$/p' ${CFG_TEMPLATE_DIR}/rfd.conf >>/etc/config/rfd.conf
      fi

      # make sure Interface 0 parameters are setup correctly
      sed -i 's|^ComPortFile =.*$|ComPortFile = /dev/mmd_bidcos|' /etc/config/rfd.conf
      sed -i 's|^#*AccessFile =.*$|AccessFile = /dev/null|' /etc/config/rfd.conf
      sed -i 's|^#*ResetFile =.*$|ResetFile = /dev/null|' /etc/config/rfd.conf

      # make sure "Improved Coprocessor Initialization" is set
      if ! grep -q "Improved Coprocessor Initialization" /etc/config/rfd.conf ; then
        sed -i 's/\[Interface 0\]/Improved\ Coprocessor\ Initialization\ =\ true\n\n&/' /etc/config/rfd.conf
      fi
    else
      echo -n "ERROR: /dev/mmd_bidcos missing, "

      # otherwise disable the whole [Interface 0] part
      sed -i -e '/^\[Interface 0\]/,/^\s*$/ s/^/#/' /etc/config/rfd.conf
    fi
  else
    # otherwise disable the whole [Interface 0] part
    sed -i -e '/^\[Interface 0\]/,/^\s*$/ s/^/#/' /etc/config/rfd.conf
  fi

  if [[ "${HM_HMRF_DEV}" == "HM-CFG-USB-2" ]]; then
    if ! grep -q "^Name.*HM-CFG-USB" /etc/config/rfd.conf; then
      inum=$(grep -c "^\[Interface .*\]" /etc/config/rfd.conf)
      {
        echo ""
        echo "[Interface ${inum+1}]"
        echo "Type = USB Interface"
        echo "Name = HM-CFG-USB"
        echo "Serial Number = ${HM_HMRF_SERIAL}"
        echo "Encryption Key ="
      } >>/etc/config/rfd.conf
    fi
  elif grep -q "^Name.*HM-CFG-USB" /etc/config/rfd.conf; then
    # otherwise disable the whole [Interface x] part
    inum=$(grep "^\[Interface .*\]" /etc/config/rfd.conf | awk '{ print $2 }' | cut -d] -f1 | tail -1)
    sed -i -e "/^\[Interface ${inum}\]/,/^\s*$/ s/^/#/" /etc/config/rfd.conf
  fi

  # Now we copy rfd.conf to /var/etc and modify things that
  # users should not override
  cp -a /etc/config/rfd.conf /var/etc/
  sed -i -e 's/^Listen\s\+Port\s*=.*$/Listen Port = 32001/' /var/etc/rfd.conf
}

waitStartupComplete() {
  STEPS=20
  for i in $(seq 1 ${STEPS}); do
    sleep 2
    echo -n "."
    RFDSTATUSPID=$(cat /var/status/rfd.status 2>&1)
    RFDPID=$(pidof rfd)
    if [[ "${RFDSTATUSPID}" == "${RFDPID}" ]]; then
      echo "OK"
      break
    fi
    if [[ ${i} -eq ${STEPS} ]]; then
      echo "ERROR"
    fi
  done
}

start() {
  echo -n "Starting rfd: "
  init
  if grep -q "^\[Interface .\]" /var/etc/rfd.conf 2>/dev/null; then
    # get the current syslog settings
    [[ -r /etc/config/syslog ]] && . /etc/config/syslog

    # adjust the oom score (which is inherited by start-stop-daemon)
    # to ensure that others are killed first in case of low memory situations
    echo -900 >/proc/$$/oom_score_adj 2>/dev/null

    start-stop-daemon -S -q -b -m -p ${PIDFILE} --exec /bin/rfd -- -f /var/etc/rfd.conf -l ${LOGLEVEL_RFD}
    waitStartupComplete
  else
    echo "no BidCos-RF hardware found"
  fi
}
stop() {
  echo -n "Stopping rfd: "
  start-stop-daemon -K -q -p ${PIDFILE}
  rm -f ${PIDFILE}
  echo "OK"
}
restart() {
  stop
  start
}

case "$1" in
  start)
    start
  ;;
  stop)
    stop
  ;;
  restart|reload)
    restart
  ;;
  *)
    echo "Usage: $0 {start|stop|restart}"
    exit 1
esac

exit 0
